<?php

function __autoload($ten){
	$ten=str_replace("_","/",$ten);
	$ten=strtolower(str_replace("Model","Models",$ten));
	if(file_exists(BASE_PATH . "/$ten.php")){
		require ("$ten.php");
	}
}

function cutstring($str, $length){
	if(!$str || !$length){
		return $str;
	}
	
	if(mb_strlen($str) > $length){
		return mb_substr($str, 0, $length, 'UTF-8') . '...';
	}else{
		return $str;
	}
}

function loadview($ten,$data=""){
	require("views/$ten.php");
}



function redirect($url){
	ob_end_clean();
	header("location:$url");
	exit();
}

function redirectjs($str,$url){

	loadview("template/header2");

	echo "<script>alert('".$str."');location.href='".$url."'</script>";

	exit();
}

function filter($string)
{
$string1=$string;
$thay='*';
return preg_replace("/(location\.)|(alert)|(document\.)|(script)|(implementation)|(livescript)|(LAYER)|(mocha)|(select)|(union)|(concat)/i", $thay, $string1);
}

if (get_magic_quotes_gpc()) {
 function stripslashes_deep($value)
 	{
       $value = is_array($value) ?
        array_map('stripslashes_deep', $value) :
                    stripslashes(filter($value));
        return $value;
	}  

	  $_POST =stripslashes_deep($_POST);
	  $_GET =stripslashes_deep($_GET);

}







 function khongdau($str) {
	 
    $str = preg_replace("/(\.|\/|_|!|>|<|^|,|;|#|%|'|:|\"|\?|=)/", '', $str);  
     $str = str_replace('\'','',$str);
    $str = str_replace('+','-',$str);  
	 $str = str_replace('—','-',$str);
	
	$str = preg_replace("(\()", '', $str);
	$str = preg_replace("(\))", '', $str); 	
   $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
	$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
	$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
	$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
	$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
	$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
	$str = preg_replace("/(đ)/", 'd', $str);
	$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
	$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
	$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
	$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
	$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
	$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
	$str = preg_replace("/(Đ)/", 'D', $str);
	$str = preg_replace("/'/", '', $str); 
	$str = preg_replace("//", '', $str); 
	$str = preg_replace("/%/", '', $str); 
	$str=trim($str);
	$str = preg_replace("(%20| )", '-', $str);
	 $str = preg_replace('/-+/','-',$str); 
	return $str; 
}

function url() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

function echo2($str)
{
	 echo htmlspecialchars($str,ENT_QUOTES,'utf-8');

}

function encode($str)
{
	 return htmlspecialchars($str,ENT_QUOTES,'utf-8');

}
function get_ip()
{
     $ip = false;
     if(!empty($_SERVER['HTTP_CLIENT_IP']))
     {
          $ip = $_SERVER['HTTP_CLIENT_IP'];
     }
     if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
     {
          $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
          if($ip)
          {
              array_unshift($ips, $ip);
               $ip = false;
          }
          for($i = 0; $i < count($ips); $i++)
          {
               if(!preg_match("/^(10|172\.16|192\.168)\./i", $ips[$i]))
               {
                    if(version_compare(phpversion(), "5.0.0", ">="))
                    {
                         if(ip2long($ips[$i]) != false)
                         {
                              $ip = $ips[$i];
                              break;
                        }

                    }

                    else

                    {

                         if(ip2long($ips[$i]) != - 1)
                         {
                              $ip = $ips[$i];
                             break;

                         }

                    }

               }

          }

     }

     return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);

}  
function randomstring($length = 10) {
    return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}

function time_ago($date)
{

	if(empty($date)){
		return "";
	}

	$periods = array("giây", "phút", "giờ", "ngày", "tuần", "tháng", "năm", "10 năm");
	$lengths = array("60","60","24","7","4.35","12","10");
	$now = time();
	$unix_date = strtotime($date);
// check validity of date
	if(empty($unix_date)) {
	return $date;
	}

// is it future date or past date

	if($now > $unix_date) {
	$difference = $now - $unix_date;
	$tense = "trước";
	} else {
	$difference = $unix_date - $now;
	$tense = "sau";}
	for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
	$difference /= $lengths[$j];
	}
	$difference = round($difference);
	if($difference != 1) {
	$periods[$j].= "";
	}
	return "$difference $periods[$j] {$tense}";

}

function url_truyen($id,$str){
	
		//return HOME."index.php?module=truyen&act=view&id=".$id;
		return HOME.'truyen/'.$str.'/'.$id.'.html';
	
}
function url_truyen_theloai($id,$str){
	
		return HOME."truyen/".$str.".html";
	
}
function url_truyen_chuong($id,$str1,$str2){
//return HOME."index.php?module=truyen&act=chuong&id=".$id;
return HOME.'truyen/'.$str2.'-'.$str1.'/'.$id.'.htm';

}
function url_truyen_tacgia($str){
		return HOME."truyen/author/".khongdau(trim($str)).".html";
		//return HOME."index.php?module=truyen&act=tacgia&val=".khongdau($str);
	
}
function url_truyen_tag($str){
		return HOME."truyen/tag/".khongdau(trim($str)).".html";
		//return HOME."index.php?module=truyen&act=tacgia&val=".khongdau($str);
	
}
function url_truyen_tag2($str){
		return HOME."truyen/tag2/".khongdau(trim($str)).".html";
		//return HOME."index.php?module=truyen&act=tacgia&val=".khongdau($str);
	
}
function url_truyen_tag3($str){
		return HOME."truyen/tag3/".khongdau(trim($str)).".html";
		//return HOME."index.php?module=truyen&act=tacgia&val=".khongdau($str);
	
}
function url_post($id,$str,$ref){

		return HOME.$ref."/".$str."/".$id.".html";
	
}
function url_album($id,$type){
	if($type=='video'){
		return HOME."video/playlist/$id.html";
	}
	
	if($type=='blog'){
		return HOME."blog/playlist/$id.html";
	}

}
function url_category($id,$str,$str2=''){
		if($str2==''){	
		return HOME.$id. '/'.$str.'.html';
		}else{
			return HOME.$str2.'/c'.$id. '/'.$str;
		//	return HOME.'index.php?module=news&act=type&type='.$str2.'&action=category&id='.$id;
		}
}
function url_subcategory($id,$str,$str2=''){
		if($str2==''){	
		return HOME.$id. '/'.$str.'.htm';
		}else{
		return HOME.$str2.'/s'.$id. '/'.$str;
		//return HOME.'index.php?module=news&act=type&type='.$str2.'&action=subcategory&id='.$id;
		}
}
function url_user($id){
return HOME."member/".$id;
}

function url_blog_user($id){
return HOME."blog/user/".$id;
}
function url_video_user($id){
return HOME."video/user/".$id;
}
function url_truyen_user($id){
return HOME."truyen/user/".$id;
}
function web_title($str,$where=''){

								
				if(isset($_GET['page'])){
					$str.= ' - Trang '.$_GET['page'];
				}
			
	return $str;

}

function web_des($str,$where=''){
							
				if(isset($_GET['page'])){
					$str.= ' Trang '.$_GET['page'];
				}
			
	return $str;

}
function web_keyword($str,$where=''){
							
				if(isset($_GET['page'])){
					$str.= ' Trang '.$_GET['page'];
				}
			
	return $str;

}

function show_username($user,$name){
	if($name !='') return $name;
	return $user;
}
function url_ajax($op=''){
	

	$url=url();

	if($op=='category'){
		
	}

	if(!isset($_GET['page'])){
		$lw=substr($url,-1);
		if($lw!='/'){
		 $url.='/';
		}
	}
	

	
	if(isset($_GET['page']) && $_GET['page']==''){
		$lw=substr($url,-1);
		if($lw!='/'){
		 $url.='/';
		}
	}
	
	if(isset($_GET['page']) && $_GET['page']!=''){
		$lw=substr($url,-1);
		if($lw!='/'){
			 $data=strrpos($url,'/');
			 $url=substr($index,0,($data+1));
		}
		
	}
	
	return $url;
}

function mycurl($data,$url){
	//open connection
	$ch = curl_init();
	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_URL, $url);
	curl_setopt($ch,CURLOPT_POST, count($data));
	curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);

	//execute post
	$result = curl_exec($ch);
	return $result;
	//close connection
	curl_close($ch);
}
function tag_post($id,$str,$category=''){
			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
											$value=trim($value);
											$tag=khongdau($value);
											
											$db->query("select * from tag where alias ='".$tag."'");
														if($db->num_rows()>0){
															$row=$db->fetchOne();
															//Update tag table
															$db->nonquery("update tag set num=num+1 where id='".$row['id']."'");
															//Handle tag_post
															$db->query('select * from tag_post where post_id='.$id.' and tag_id='.$row['id']);
																if($db->num_rows()>0){
																
																}else{
																	
																 	$db->nonquery("insert into tag_post(tag_id,post_id) values(".$row['id'].",".$id.")");
																}
														
														}else{
															if($category !=''){
															$db->nonquery("insert into tag(name,alias,num,category) values('".$value."','".$tag."',1,".$category.")");
															}else{
															$db->nonquery("insert into tag(name,alias,num) values('".$value."','".$tag."',1)");
														
															}
															$tag_id=$db->get_insert_id();
															
															$db->nonquery("insert into tag_post(tag_id,post_id) values(".$tag_id.",".$id.")");
															
															
														}
										}
						$db->close();
							
				}

}


function truyen_tag($id,$str){
			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
											$value=trim($value);
											$tag=khongdau($value);
											
											$db->query("select * from truyen_tag where alias ='".$tag."'");
											
														if($db->num_rows()>0){
															$row=$db->fetchOne();
														
															
															//Handle tag_post
															$db->query('select * from truyen_tag_fk where truyen_id='.$id.' and tag_id='.$row['id']);
															
																if($db->num_rows()>0){
																
																}else{
																	
																 	$db->nonquery("insert into truyen_tag_fk(tag_id,truyen_id) values(".$row['id'].",".$id.")");
																
																}
														
														}else{
														
															$db->nonquery("insert into truyen_tag(name,alias) values('".$value."','".$tag."')");
														
														
															$tag_id=$db->get_insert_id();
															
															$db->nonquery("insert into truyen_tag_fk(tag_id,truyen_id) values(".$tag_id.",".$id.")");
															
															
														}
										}
										
						$db->close();
							
				}

}


function truyen_get_tag($str){
			if($str){
					
					
							$tagar=explode(",",$str);
							$tag="";
										foreach($tagar as $value ){
											$value=trim($value);
											$tag.="<a href='".url_truyen_tag(khongdau($value))."'>$value</a> ,";
																								
										}
										
					return substr($tag,0,strlen($tag)-1);
							
				}

}

function truyen_tacgia($id,$str){
			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
											$value=trim($value);
											$tag=khongdau($value);
											
											$db->query("select * from truyen_tacgia where alias ='".$tag."'");
														if($db->num_rows()>0){
															$row=$db->fetchOne();
														
															
															//Handle tag_post
															$db->query('select * from truyen_tacgia_fk where truyen_id='.$id.' and tacgia_id='.$row['id']);
																if($db->num_rows()>0){
																
																}else{
																	
																 	$db->nonquery("insert into truyen_tacgia_fk(tacgia_id,truyen_id) values(".$row['id'].",".$id.")");
																}
														
														}else{
														
															$db->nonquery("insert into truyen_tacgia(ten,alias) values('".$value."','".$tag."')");
														
															
															$tag_id=$db->get_insert_id();
															
															$db->nonquery("insert into truyen_tacgia_fk(tacgia_id,truyen_id) values(".$tag_id.",".$id.")");
															
															
														}
										}
										
						$db->close();
							
				}

}

function truyen_theloai($id,$str){
			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
													$tag=intval($value);
													//Handle tag_post
															$db->query('select * from truyen_theloai_fk where truyen_id='.$id.' and theloai_id='.$tag);
																if($db->num_rows()>0){
																	}else{
																	
																 	$db->nonquery("insert into truyen_theloai_fk(theloai_id,truyen_id) values(".$tag.",".$id.")");
															}
												
										}
										
						$db->close();
							
				}

}

function get_row(){
	$cache=new cache;
	$dt=$cache->load('select count(*) as num from index_post');
	if(!$dt){
	$db=new db;
	$db->connect();
	$db->query("select count(*) as num from index_post");
	$row=$db->fetchOne();
	$dt=$row['num'];
	$cache->save("select count(*) as num from index_post",$dt,300);
	}
	return $dt;
}





function recursive($sourceArr, $parents = 0, $level = 1, &$resultArr){
	if(count($sourceArr)>0){
		foreach ($sourceArr as $key => $value){
			if($value['p_id'] == $parents){
				$value['level'] = $level;
				$resultArr[] = $value;
				$newParents = $value['id'];
				unset($sourceArr[$key]);
				recursive($sourceArr, $newParents, $level + 1, $resultArr);
			}
		}
	}
}

function cmsSelect($name, $value = null, $options, $attribs = array() ){
	$strAttribs = '';
	if(count($attribs)>0){
		foreach ($attribs as $keyAttribs => $valueAttribs){
			$strAttribs .= $keyAttribs . '="' . $valueAttribs . '" ';
		}
	}

	$xhtml = '<select name="' . $name . '" id="' . $name . '" ' . $strAttribs . ' >';
	$xhtml .= '<option value="">--Tùy chọn danh mục--</option>';
	if($options){
		foreach ($options as $key=> $info){
			$strSelect = '';
			if($info['id'] == $value){
				$strSelect = 'selected="selected"';
			}

			if($info['level'] == 1){
				$xhtml .= '<option value="' . $info['id'] . '" ' . $strSelect . '>+ ' . $info['name'] . '</option>';
			}else{
				$string = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
				$newString = '';
				for($i=1;$i<$info['level']; $i++){
					$newString .= $string;
				}
				$info['name'] = $newString . '- ' . $info['name'];
				$xhtml .= '<option value="' . $info['id'] . '" ' . $strSelect . '> ' . $info['name'] . '</option>';
			}
		}
	}

	$xhtml .= '</select>';

	return $xhtml;
}



function remove_dir($dir) { 
    if (!is_dir($dir) || is_link($dir)) return unlink($dir); 
        foreach (scandir($dir) as $file) { 
            if ($file == '.' || $file == '..') continue; 
            if (!remove_dir($dir . DIRECTORY_SEPARATOR . $file)) { 
                chmod($dir . DIRECTORY_SEPARATOR . $file, 0777); 
                if (!remove_dir($dir . DIRECTORY_SEPARATOR . $file)) return false; 
            }; 
        } 
        return rmdir($dir); 
    } 

class shareCount {
private $url,$timeout;
function __construct($url,$timeout=10) {
$this->url=rawurlencode($url);
$this->timeout=$timeout;
}

function get_fb() {
$json_string = $this->file_get_contents_curl('http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls='.$this->url);
$json = json_decode($json_string, true);

$data['like']= isset($json[0]['total_count'])?intval($json[0]['total_count']):0;
$data['comment']= isset($json[0]['commentsbox_count'])?intval($json[0]['commentsbox_count']):0;
return $data;
}
private function file_get_contents_curl($url){
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$cont = curl_exec($ch);
if(curl_error($ch))
{
die(curl_error($ch));
}
return $cont;
}
}


function blog_image_lazy($data,$name){
$data = mb_convert_encoding($data, 'HTML-ENTITIES', "UTF-8"); 
$dom = new DOMDocument;
 $dom->loadHTML($data); 
 $sxe = simplexml_import_dom($dom);

	 foreach ($sxe->xpath('//img[@src]') as $a)
	 {	
	 	
		$link= $a['src'];
		$a['class'] = 'lazy img-responsive';
		$a['data-original']=$link;
		$a['title']=$name;
		$a['src']='http://localhost/mong/public/images/loading11.gif';
		
		
	 }
 $new_html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML()); 
 return html_entity_decode($new_html,ENT_QUOTES,"UTF-8");

 }
function short_str($content,$num){ 
	if(strlen($content) < $num){
	return $content;
	}else{
	//$pos=mb_strpos($content, ' ', $num);
	return mb_substr($content,0,$num, 'UTF-8' ) . '...'; 
	}
}

function check_search(){
	$cache=new cache;
	$time=$cache->load("truyen_search1","home");
	if(!$time){
		
		$db=new db;
		$db->connect();
		$db->query("select count(id) from truyensearch");
		if($db->num_rows()==0){
			$db->query("drop table truyensearch");
			$db->query("CREATE TABLE  `truyensearch` (`id` INT( 8 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `ten` VARCHAR( 150 ) NOT NULL , `alias` VARCHAR( 150 ) NOT NULL ) ENGINE = MEMORY ");
			$db->nonquery(" INSERT truyensearch SELECT id,ten,alias FROM truyen");
			$db->close();
		}
	$cache->save("truyen_search",1,10000,'home');
	}
	

}

function static_admin(){
						$cache=new cache;
						$dt=$cache->load('static'.$_SESSION['user']['group_id'],'home');
						if(!$dt){
						$i=0;
						$j=0;
						$k=0;
						$db=new db;
						$db->connect();
						$db->query("select id from truyen where duyet=0");
						$dt['duyet']= $db->num_rows();
						$j=$j+$dt['duyet'];
						$i=$i+$dt['duyet'];
						$db->query("select id from truyen where xoa=1");
						$dt['xoa']=$db->num_rows();
						$j=$j+$dt['xoa'];
						$db->query("select id from truyen_chuong where xoa=1");
						$dt['xoachuong']=$db->num_rows();
						$j=$j+$dt['xoachuong'];
						$i=$i+$dt['xoachuong'];
						$db->query("select id from register_upload where duyet=0");
						$dt['duyetupload']=$db->num_rows();
						$j=$j+$dt['duyetupload'];
						$i=$i+$dt['duyetupload'];
						$db->query("select id from report_truyen where xuly=0");
						$dt['reporttruyen']=$db->num_rows();
						$k=	$dt['reporttruyen'];
						$j=$j+$k;
						$i=$i+$k;
						$db->close();
						$dt['k']=$k;
						$dt['i']=$i;
						$dt['j']=$j;
						
						
						$cache->save('static'.$_SESSION['user']['group_id'],$dt,300,'home');
						}
						?>
							<li class="dropdown">
						<a class="btn dropdown-toggle" data-toggle="dropdown" >
							<i class="fa fa-bell-o"></i> Xử Lý <span class="badge"><?php if($_SESSION['user']['level']==3){ echo $dt['k'];}else if($_SESSION['user']['level']==2){ echo $dt['i'];}else{ echo $dt['j'];} ?></span>
						</a>
							<ul class="dropdown-menu">
                             <?php if($_SESSION['user']['level']==2||$_SESSION['user']['level']==1){ ?>	
                                       <li><a href="<?php echo HOME;?>index.php?module=user&act=truyen&type=truyen&ext=duyet">Duyệt  Truyện <span class="badge"><?php echo $dt['duyet']; ?></span></a></li>
                                        <?php if($_SESSION['user']['level']==1){ ?>	
                                       				<li><a href="<?php echo HOME;?>index.php?module=user&act=truyen&type=truyen&ext=xoa">Xóa Truyện <span class="badge"><?php echo $dt['xoa']; ?></span></a></li>
                                       <?php }?>
                                       <li><a href="<?php echo HOME; ?>index.php?module=user&act=truyen&type=chuong&ext=xoa">Xóa Chương <span class="badge"><?php echo $dt['xoachuong']; ?></span></a></li>
                                       <li><a href="<?php echo HOME; ?>index.php?module=user&act=truyen&type=duyetupload">Đăng Ký Upload <span class="badge"><?php echo $dt['duyetupload']; ?></span></a></li>
                               <?php } ?>
                               <li><a href="<?php echo HOME; ?>index.php?module=user&act=truyen&type=reporttruyen&ext=xuly" >Report Truyện <span class="badge"><?php echo $dt['reporttruyen']; ?></span></a></li> 
                     				
						</ul>
					</li><?php
}
function inbox(){
					$user=cache_get_user($_SESSION['user']['username']);
			
					?>
                	<li><a href="<?php echo url_user($_SESSION['user']['username']) ?>">Inbox <span class="badge"><?php echo $user['inbox'] ?></span></a></li><?php
                    
}
function direct_url(){
		$url=url();
		if(isset($_GET['page']) && $_GET['page']==1){
			$le=strlen($url);
			
			if(substr($url,$le-1,1)==1){
			$str2=substr($url,0,$le-2);
			redirect($str2);
			exit();
			}
			
		}
}
function table_chuong($id){
$num=ceil($id/50000);
return "truyen_chuong_noidung".$num;	
}

function check_null($var){
	if(trim($var)){
		return $var;
		}else{return NULL;}
	}
	
function get_group($id){
	switch($id){
		case "1" : $str="Administrator"; break;
		case "2" : $str="Editor" ; break;
		case "3" :	$str="Uploader"; break;
		case "4" : $str="Member";break;
	}
	return $str;
}
function get_avatar($str1,$str2){
	if($str1 !=''){
				$ava=explode("_",$str1);
 				 $str=AVATAR."100/".$ava[0]."/".$ava['1']."/".$ava['2']."/".$str1;
	}else
	if($str2!=''){
				$str="https://graph.facebook.com/".$str2."/picture";
	}
	   return "<img src='".$str."' class='img-circle img-responsive' style='max-width:50px' />";
	 
}
function set_userinfo($str){
	if($str!=''){
	return $str;
	}else{
	return "?";
	}
}
function set_username($str1,$str2){
 if($str1!=''){ return $str1; }else{return $str2;}
}

function valid_facebook($facebook_token, $facebook_id,$email)
 {
  $ch = curl_init();
  $url="https://graph.facebook.com/me?access_token=".$facebook_token;
  curl_setopt($ch, CURLOPT_URL,$url );
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  // The following ensures SSL always works. A little detail:
  // SSL does two things at once:
  //  1. it encrypts communication
  //  2. it ensures the target party is who it claims to be.
  // In short, if the following code is allowed, CURL won't check if the
  // certificate is known and valid, however, it still encrypts communication.
  curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
  curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
  $result = curl_exec($ch);
  
  curl_close($ch);
  $fb_profile = json_decode( $result, true);

  if(isset($fb_profile['error'] ) )
  {
return false;
  }
  elseif( isset($fb_profile['id']) && $fb_profile['id'] != $facebook_id )//Check if this auth token has the same ID sent.
  {
	  return false;
 
  }
  if($fb_profile['email']!=$email){
  return false;
  }
return true;

 }
 
 
 function gtags($name){
 $nam=trim($name);
$str="doc truyen truc tuyen,đọc truyện online,đoc truyen tren dien thoai,doc truyen tren android,doc truyen tren iphone,doc truyen ".$name." tron bo,doc truyen ".$name." full,doc truyen ".$name." tren di dong,doc truyen ".$name.",".$name." full,doc truyen ".$name." tren dien thoai,download ebook ".$name." full,download truyen ".$name." full,download truyen ".$name." full pdf,download truyen ".$name." full prc";
 return $str;
 }
 
 function gtags_link($str){
 	if($str){
					
					
							$tagar=explode(",",$str);
							$tag="";
										foreach($tagar as $value ){
											$value=trim($value);
											$tag.="<a href='".url_truyen_tag(khongdau($value))."'>$value</a> ,";
																								
										}
										
					return substr($tag,0,strlen($tag)-1);
							
				}
 }
 
 function gtags_add($str,$id){
	 			if($str){
					
						$db=new db;
						$db->connect();
							$tagar=explode(",",$str);
										foreach($tagar as $value ){
											$value=trim($value);
											$tag=khongdau($value);
											
											$db->query("select * from truyen_tag where alias ='".$tag."'");
											
														if($db->num_rows()>0){
															$row=$db->fetchOne();
															
															//Neu ton tai roi thi update num = num+1;
															$db->nonquery('update truyen_tag set num=num+1 where id='.$row['id']);
														
															
															//Handle tag_post
																$db->query('select * from truyen_tag_fk where truyen_id='.$id.' and tag_id='.$row['id']);
															
																if($db->num_rows()>0){
																
																}else{
																	
																 	$db->nonquery("insert into truyen_tag_fk(tag_id,truyen_id) values(".$row['id'].",".$id.")");
																
																}
														
														}else{
														
															$db->nonquery("insert into truyen_tag(name,alias) values('".$value."','".$tag."')");
																	
															$tag_id=$db->get_insert_id();
															$db->nonquery("insert into truyen_tag_fk(tag_id,truyen_id) values(".$tag_id.",".$id.")");
															
															
														}
										}
										
						$db->nonquery("update truyen set gtags=1 where id=".$id);				
						$db->close();
							
				}

 }

